<?php

class MaterialController extends Controller {
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array(
				'allow',
				// allow all users to perform 'index' and 'view' actions
				'actions' => array(
					'tags',
					'search'
				),
				'users' => array(
					'@'
				),
			),
			array(
				'allow',
				// allow all users to perform 'index' and 'view' actions
				'actions' => array(
					'index',
					'view'
				),
				'roles' => array(
					'materialView'
				),
			),
			array(
				'allow',
				// allow admin user to perform 'admin' and 'delete' actions
				'actions' => array(
					'create',
					'createAltName',
					'deleteAltName',
					'createTag',
					'deleteTag',
					'update',
					'admin',
					'delete',
					'updateModels',
					'deleteModel',
				),
				'roles' => array(
					'materialManage'
				),
			),
			array(
				'deny',
				// deny all users
				'users' => array(
					'*'
				),
			),
		);
	}

	public function actions() {
		return array(
			'search' => array(
				'class' => 'web.controllers.material.SearchMaterialAction',
			),
			'updateModels' => array(
				'class' => 'web.controllers.material.UpdateMaterialModelsAction',
			),
		);
	}

	public function actionTags($term) {
		$criteria = new CDbCriteria();

		$criteria->compare('name', $term, true);
		$criteria->limit = 10;
		$tags = MaterialTag::model()->findAll($criteria);
		$returnVal = array();
		foreach ($tags as $tag) {
			$returnVal[] = array(
				'label' => $tag->getAttribute('name'),
				'id' => $tag->getAttribute('id'),
			);
		}
		header("Cache-Control: no-cache, must-revalidate");
		header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
		echo CJSON::encode($returnVal);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {
		$this->render('view', array(
				'model' => $this->loadModel($id),
			));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate() {
		$model = new Material;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['Material'])) {
			$model->attributes = $_POST['Material'];
			if ($model->save())
				$this->redirect(array(
						'view',
						'id' => $model->id
					));
		}

		$this->render('create', array(
				'model' => $model,
			));
	}
	public function actionCreateAltName() {
		$model = new MaterialAltName();

		if (isset($_POST['MaterialAltName'])) {
			$model->attributes = $_POST['MaterialAltName'];
			$model->save();
			$this->redirect(array(
					'view',
					'id' => $model->materialId
				));
		}
		throw new CHttpException(401);
	}
	public function actionCreateTag($materialId) {
		$model = new MaterialTag();
		if (isset($_POST['MaterialTag'])) {
			$model->attributes = $_POST['MaterialTag'];
			$model->name = trim($model->name);
			$existTag = MaterialTag::model()
				->findByAttributes(array(
					'name' => $model->name
				));
			if ($existTag) {
				$relationExist = MaterialTagMaterial::model()
					->findByAttributes(
						array(
							'materialId' => $materialId,
							'tagId' => $existTag->id
						));
				if (!$relationExist) {
					$relation = new MaterialTagMaterial();
					$relation->materialId = $materialId;
					$relation->tagId = $existTag->id;
					$relation->save();
				}
			} else {
				if ($model->save()) {
					$relation = new MaterialTagMaterial();
					$relation->materialId = $materialId;
					$relation->tagId = $model->id;
					$relation->save();
				}
			}
			$this->redirect(array(
					'view',
					'id' => $materialId
				));
		}
		throw new CHttpException(401);
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		$model = $this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['Material'])) {
			$model->attributes = $_POST['Material'];
			if ($model->save())
				$this->redirect(array(
						'view',
						'id' => $model->id
					));
		}

		$this->render('update', array(
				'model' => $model,
			));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (!isset($_GET['ajax']))
				$this
					->redirect(
						isset($_POST['returnUrl']) ? $_POST['returnUrl']
							: array(
								'admin'
							));
		} else
			throw new CHttpException(400,
				'Invalid request. Please do not repeat this request again.');
	}

	public function actionDeleteModel($id) {
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$altName = MaterialModel::model()->findByPk($id);
			$materialId = $altName->materialId;
			$altName->delete();
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (!isset($_GET['ajax']))
				$this
					->redirect(
						isset($_POST['returnUrl']) ? $_POST['returnUrl']
							: array(
								'updateModels',
								'id' => $materialId,
							));
		} else
			throw new CHttpException(400,
				'Invalid request. Please do not repeat this request again.');
	}

	public function actionDeleteAltName($id) {
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$altName = MaterialAltName::model()->findByPk($id);
			$materialId = $altName->materialId;
			$altName->delete();
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (!isset($_GET['ajax']))
				$this
					->redirect(
						isset($_POST['returnUrl']) ? $_POST['returnUrl']
							: array(
								'view',
								'id' => $materialId,
							));
		} else
			throw new CHttpException(400,
				'Invalid request. Please do not repeat this request again.');
	}
	public function actionDeleteTag($materialId, $tagId) {
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$tagMaterial = MaterialTagMaterial::model()
				->findByAttributes(
					array(
						'materialId' => $materialId,
						'tagId' => $tagId
					));
			$tagMaterial->delete();
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (!isset($_GET['ajax']))
				$this
					->redirect(
						isset($_POST['returnUrl']) ? $_POST['returnUrl']
							: array(
								'view',
								'id' => $materialId,
							));
		} else
			throw new CHttpException(400,
				'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		$searchModel = new MaterialSearch();
		$searchModel->unsetAttributes(); // clear any default values
		if (isset($_GET['MaterialSearch'])) {
			$searchModel->attributes = $_GET['MaterialSearch'];
		}
		$dataProvider = new CActiveDataProvider('Material',
			array(
				'criteria' => $searchModel->createCriteria()
			));
		$this
			->render('index',
				array(
					'dataProvider' => $dataProvider,
					'searchModel' => $searchModel
				));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$model = new Material('search');
		$model->unsetAttributes(); // clear any default values
		if (isset($_GET['Material']))
			$model->attributes = $_GET['Material'];

		$this->render('admin', array(
				'model' => $model,
			));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id) {
		$model = Material::model()->findByPk($id);
		if ($model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'material-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
